<?php

namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\captcha\CaptchaValidator;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%user}}".
 *
 * @property int $id
 * @property string $username 管理员登录名
 * @property string $auth_key 认证密钥
 * @property string $password_hash 管理员密码
 * @property string $password_reset_token 重置密码密钥
 * @property string $email 管理员邮箱
 * @property string $identity 身份 user普通用户 admin管理员  root超级管理员(初始化数据)
 * @property int $status 管理员状态
 * @property int $created_at
 * @property int $updated_at
 */
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
    const STATUS_ACTIVE = 1;
    public static $username = '';
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['created_at', 'updated_at'], 'required'],
            [['username', 'password_hash', 'password_reset_token', 'email', 'identity'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['username'], 'unique'],
            [['email'], 'unique'],
            [['password_reset_token'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Password Hash',
            'password_reset_token' => 'Password Reset Token',
            'email' => 'Email',
            'identity' => 'Identity',
            'status' => 'Status',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {
        return $this->authKey;
    }

    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    public function login()
    {
        $captcha = new CaptchaValidator();
        $captcha->captchaAction = 'auth/captcha';
        if(!$captcha->validate(Yii::$app->request->post('code'))){
            $this->addErrors(['对不起，验证码错误！']);
            return false;
        }
        if (!$admin = static::findByUsername($this->username)) {
            $this->addErrors(['对不起，该管理员不存在！']);
            return false;
        }
        if (0 == $admin->status) {
            $this->addErrors(['对不起，该管理员已被禁用！']);
            return false;
        }
        if($admin->validatePassword($this->password_hash)){
            return Yii::$app->user->login(static::findByUsername($this->username), 0);
        }
        $this->addErrors(['对不起，密码错误！']);
        return false;
    }
}
